<!--
 * @Author: C.
 * @Date: 2023-04-14 13:13:22
-->
<template>
  <span class="mr-3">
    <slot></slot>
  </span>

  <!-- <DropdownButton
    type="primary"
    class="mr-3"
    v-if="props.transformActions.length > 1"
    @click="transformTo({ key: `${props.transformActions[0].to}` })"
    :disabled="disabledTransformBill"
  >
    <template #overlay>
      <Menu @click="transformTo">
        <MenuItem
          v-for="item in props.transformActions.slice(1)"
          :key="item.to"
          :disabled="item.disabled"
          :title="item.label"
          :icon="item.icon"
        >
          <Icon :icon="item.icon" v-if="item.icon" />
          {{ item.label }}
        </MenuItem>
      </Menu>
    </template>
    {{ props.transformActions[0].label }}
    <template #icon>
      <Icon icon="ant-design:down-outlined" />
    </template>
  </DropdownButton> -->

  <a-button
    v-for="(item, i) in props.transformActions"
    :key="i"
    type="primary"
    class="mr-3"
    @click="transformTo({ key: `${item.to}`, data: item.data ? item.data : {} })"
    :disabled="disabledTransformBill"
  >
    {{ item.label }}
  </a-button>

  <Dropdown type="primary" class="mr-3" :loading="loadingRef">
    <template #overlay>
      <Menu @click="handleMenuClick">
        <MenuItem
          v-for="item in btnOptions"
          :key="item.value"
          :disabled="item.disabled"
          :title="item.label"
          :icon="item.icon"
        >
          <Icon :icon="item.icon" v-if="item.icon" />
          {{ item.label }}
        </MenuItem>
      </Menu>
    </template>
    <a-button type="primary"> 审批<Icon icon="ant-design:down-outlined" /> </a-button>
  </Dropdown>
  <Dropdown type="primary" class="mr-3" :loading="loadingRef">
    <template #overlay>
      <Menu @click="handleOptionClick">
        <MenuItem
          v-for="item in BillOptions"
          :key="item.value"
          :disabled="item.disabled"
          :title="item.label"
          :icon="item.icon"
        >
          <Icon :icon="item.icon" v-if="item.icon" />
          {{ item.label }}
        </MenuItem>
      </Menu>
    </template>
    <a-button type="primary"> 操作<Icon icon="ant-design:down-outlined" /> </a-button>
  </Dropdown>

  <!-- <a-button type="primary" @click="toEdit" class="mr-3">
    {{ t('common.edit') }}
  </a-button> -->
  <a-button @click="refreshPage"> 刷新 </a-button>
  <FormModal
    title="添加备注"
    width="40%"
    @register="registerRemarkModal"
    @success="getRemarkToAudit"
  />
</template>

<script lang="ts" setup>
  import { PropType, computed, unref, ref } from 'vue';
  import { MenuItem, Menu, Dropdown } from 'ant-design-vue';
  import { batchConfirm as warningBatchConfirm } from '/@/jv_package/components/AuditController/src/index';
  import Icon from '/@/components/Icon';
  import { createApiModule } from '/~/utils/help/createApiModule';
  import { getBtnOption } from './help';
  import { useAppRouter } from '/~/hooks/help/useAppRouter';
  import { apiEnum } from '/~/maps/apis';
  import { INode } from '../../AuditFlow/src/types';
  import { FormModal, useFormModel } from '/~/components/FormModel';
  import { getFormMaps } from '/~/utils/help/createFields';
  const { closeTo, close, push, refreshPage } = useAppRouter();
  import { batchConfirm } from '/~/utils/system/index';
  import { ResultEnum } from '/@/enums/httpEnum';
  // const { t } = useI18n();
  const emit = defineEmits(['change']);
  const [registerRemarkModal, remarkAction] = useFormModel({
    schemas: getFormMaps([
      [
        'Remarks',
        {
          component: 'InputTextArea',
          required: true,
          defaultValue: '',
          componentProps: {
            rows: 8,
            maxlength: 150,
            showCount: true,
            allowClear: true,
          },
        },
      ],
    ]),
    labelWidth: 100,
    baseColProps: { span: 24 },
    showActionButtonGroup: false,
  });
  const loadingRef = ref(false);
  const temporaryKey = ref('');
  const props = defineProps({
    // api前缀 api-name
    apiName: String as PropType<string>,
    // // 状态码 state
    mode: {
      type: Number as PropType<number>,
      default: 0,
    },
    // 单据key bill-key
    billKey: String as PropType<string>,
    billId: String as PropType<string>,
    // 审核流
    process: {
      type: Array as PropType<INode[]>,
    },
    state: String as PropType<string>,
    transformActions: {
      type: Array as PropType<
        {
          label: string;
          to: string;
          data?: Function;
          icon?: string;
          disabled?: boolean;
        }[]
      >,
      default: () => [],
    },
  });
  const btnOptions = computed(() => {
    return getBtnOption(props.mode || 0, apiEnum.AUDITS);
  });
  const BillOptions = computed(() => {
    const redo = {
      disabled: false,
      label: '另做',
      value: 'redo',
    };
    // console.log(getBtnOption(props.mode || 0, apiEnum.OPTIONS), 55);

    return [...getBtnOption(props.mode || 0, apiEnum.OPTIONS), redo];
  });
  const disabledTransformBill = computed(() => {
    return props.state !== 'Approved';
  });
  const requiredRemarkOperation = computed(() => {
    // return ['withdraw', 'discard', 'reject', 'audit'];
    if (!props.process) return [];
    // props.process
    let currentNode = props.process.find((item) => {
      return item.ApproveState === 'WaitToProcess';
    });
    return currentNode?.RemarkSets ?? [];
  });
  const ModuleApi = computed(() => {
    if (!props.apiName) return {};
    return createApiModule(props.apiName);
  });
  // 按钮事件汇总
  async function handleMenuClick(e) {
    if (requiredRemarkOperation.value.includes(e.key)) {
      temporaryKey.value = e.key;
      remarkAction.openModal(true, {
        formData: {
          Remarks: '',
        },
      });
    } else {
      todoAuditApi(e.key);
    }
  }
  function getRemarkToAudit(params: Recordable) {
    // console.log(params.Remarks);
    todoAuditApi(temporaryKey.value, params.Remarks);
  }
  // 接口调用
  function todoAuditApi(key, Remarks = '') {
    if (!props.apiName) return;
    loadingRef.value = true;
    const params = {
      Ids: [props.billId],
      BillId: props.billId,
      Remarks,
    };
    unref(ModuleApi)
      [`api_${key}`](params)
      .then((res) => {
        let _res = res?.Code == ResultEnum.ERROR;
        if (key == 'delete') {
          !_res && close();
          return;
        }
        emit('change');
      })
      .finally((_) => {
        loadingRef.value = false;
      });
  }
  // 删除和编辑事件
  function handleOptionClick(e) {
    if (e.key === 'save') {
      toEdit();
    } else if (e.key === 'redo') {
      toEdit('redo');
    } else if (e.key === 'delete') {
      // toEdit('redo');
      batchConfirm([props.billId], () => {
        handleMenuClick(e);
      });
    } else {
      handleMenuClick(e);
    }
  }
  function toEdit(redo?: any) {
    closeTo({
      name: `${props.billKey}_Edit`,

      query: {
        Id: props.billId,
        redo,
      },
    });
  }
  function transformTo(e) {
    let data;
    if (JSON.stringify(e.data) !== '{}') {
      data = e.data();
    }
    if (data && data.info && data.flag) {
      warningBatchConfirm(data, () => {
        _routerPush(e);
      });
    } else {
      _routerPush(e);
    }

    // const
  }

  function _routerPush(e) {
    push({
      name: `${e.key}_Edit`,
      query: {
        TransformId: props.billId,
        ApiName: props.apiName,
        BillKey: props.billKey,
      },
    });
  }
</script>
<style lang="less" scoped></style>
